﻿using System;
using System.Data;

namespace GT
{
    public static partial class Extensions
    {
        public static bool HasRecords(this DataTable table)
        {
            return (table.Rows.Count > 0);
        }

        public static DataTable SelectDistinct(this DataTable SourceTable, String FieldName)
        {
            return SelectDistinct(SourceTable, FieldName, String.Empty);
        }

        public static DataTable SelectDistinct(this DataTable SourceTable, String FieldNames, String Filter)
        {
            DataTable dt = new DataTable();
            String[] arrFieldNames = FieldNames.Replace(" ", "").Split(',');
            foreach (String s in arrFieldNames)
            {
                if (SourceTable.Columns.Contains(s))
                    dt.Columns.Add(s, SourceTable.Columns[s].DataType);
                else
                    throw new Exception(String.Format("The column {0} does not exist.", s));
            }

            Object[] LastValues = null;
            foreach (DataRow dr in SourceTable.Select(Filter, FieldNames))
            {
                Object[] NewValues = GetRowFields(dr, arrFieldNames);
                if (LastValues == null || !(ObjectComparison(LastValues, NewValues)))
                {
                    LastValues = NewValues;
                    dt.Rows.Add(LastValues);
                }
            }

            return dt;
        }

        public static DataTable SelectRows(this DataTable dt, string whereExpression, string orderByExpression)
        {
            dt.DefaultView.RowFilter = whereExpression;
            dt.DefaultView.Sort = orderByExpression;
            return dt.DefaultView.ToTable();
        }

    }
}
